//
//  UITextField+AYExtension.m
//  CreateTools
//
//  Created by AY on 16/6/27.
//  Copyright © 2016年 Jasperay. All rights reserved.
//

#import "UITextField+AYExtension.h"
#import <objc/message.h>

@implementation UITextField (AYExtension)

/** 通过这个属性名，就可以修改textField内部的占位文字颜色 */
static NSString * const LXPlaceholderColorKeyPath = @"placeholderLabel.textColor";
static NSString * kObjectPropertyKey = @"kObjectPropertyKey";

/**
 *  设置占位文字颜色
 */
- (void)setAy_placeholderColor:(UIColor *)lx_placeholderColor
{
    // 这3行代码的作用：1> 保证创建出placeholderLabel，2> 保留曾经设置过的占位文字
    NSString *placeholder = self.placeholder;
    self.placeholder = @" ";
    self.placeholder = placeholder;
    
    // 处理xmg_placeholderColor为nil的情况：如果是nil，恢复成默认的占位文字颜色
    if (lx_placeholderColor == nil) {
        lx_placeholderColor = [UIColor colorWithRed:0 green:0 blue:0.0980392 alpha:0.22];
    }
    
    // 设置占位文字颜色
    [self setValue:lx_placeholderColor forKeyPath:LXPlaceholderColorKeyPath];
}

/**
 *  获得占位文字颜色
 */
- (UIColor *)ay_placeholderColor
{
    return [self valueForKeyPath:LXPlaceholderColorKeyPath];
}


- (void)setAy_maxLength:(NSInteger)ay_maxLenth
{
    objc_setAssociatedObject(self, &kObjectPropertyKey, [NSString stringWithFormat:@"%ld",(long)ay_maxLenth], OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    [self addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
}

- (NSInteger)ay_maxLength
{
    return [objc_getAssociatedObject(self, &kObjectPropertyKey) integerValue];
}


- (void)textFieldDidChange:(UITextField *)noti{
    
    UITextField *textField = noti;
    
    NSString *toBeString = textField.text;
    NSString *lang = [textField.textInputMode primaryLanguage];
    if ([lang isEqualToString:@"zh-Hans"])// 简体中文输入
    {
        //获取高亮部分
        UITextRange *selectedRange = [textField markedTextRange];
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position)
        {
            if (toBeString.length > self.ay_maxLength)
            {
                textField.text = [toBeString substringToIndex:self.ay_maxLength];
            }
        }
        
    }
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else
    {
        if (toBeString.length > self.ay_maxLength)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:self.ay_maxLength];
            if (rangeIndex.length == 1)
            {
                textField.text = [toBeString substringToIndex:self.ay_maxLength];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.ay_maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}



@end
